package vip.xiaonuo.hontu.util;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Encoder;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.util.HttpUtil;
import vip.xiaonuo.hontu.config.FileServerConfig;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Slf4j
public class NetImg2Base64 {

    public static String toBase64Url( String imgURL ){
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        byte[] buffer = null;
        try {
            // 创建URL
            URL url = new URL(imgURL);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            inputStream = conn.getInputStream();
            outputStream = new ByteArrayOutputStream();
            // 将内容读取内存中
            buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            buffer = outputStream.toByteArray();
            // 对字节数组Base64编码
            return "data:image/jpg;base64," + new BASE64Encoder().encode(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    // 关闭outputStream流
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String getFileServerUrl(String url){
        String requestUrl = FileServerConfig.getServerUrl();
        File file = null;
        try {
            file = urlToMultipartFile(url, UUID.randomUUID().toString()+".jpg");
            List<File> fileList = new ArrayList<>();
            fileList.add(file);

            Map<String , Object> param = new HashMap<>();
            String deptCode = ConstantContextHolder.getSysConfig("DEPT_CODE", String.class, true);
            String tenantCode = ConstantContextHolder.getSysConfig("TENANT_CODE", String.class, true);
            param.put("tenantCode",tenantCode);
            param.put("deptCode",deptCode);
            Response response = HttpUtil.getInstance().postMultipartFormData(requestUrl, param , fileList, "file");
            if (Objects.nonNull(response) && response.isSuccessful()) {
                FileResponse data = JSON.parseObject(response.body().string(),FileResponse.class);
                String serverFileUrl = data.getData().getUrl();
                log.info("文件服务返回地址：{}",serverFileUrl);
                Thread.sleep(100);
                return serverFileUrl;
            }
            log.info("文件地址：{}",url);
            throw new RuntimeException();
        } catch (Exception e) {
            log.error("请求地址：{}",requestUrl);
            throw new RuntimeException(e);
        }finally{
            if(file!=null && file.exists()){
                file.delete();
            }
        }
    }


    /**
     * url转MultipartFile
     * @param url
     * @return
     * @throws Exception
     */
    public static File urlToMultipartFile(String url,String fileName) throws Exception {
        log.info("urlToMultipartFile文件转换中，url为："+url+"文件名称为："+fileName);
        File file = null;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.connect();
            log.info("成功建立httpUrl连接"+httpUrl.getURL().toString());
            file = inputStreamToFile(httpUrl.getInputStream(),fileName);
        } catch (Exception e) {
            log.error("file.url:{}" , url);
            e.printStackTrace();
        }
        return file;
    }
    /**
     * inputStream 转 File
     * @param ins
     * @param name
     * @return
     * @throws Exception
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception{
        log.info("inputStream 转 File中"+name);
        File file = new File("D:"+File.separator+"temp" + File.separator + name);
        if(!file.exists()){
            file.createNewFile();
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        log.info("inputStream 转 File转换完成"+name);
        return file;
    }

    /**
     * file转multipartFile
     * @param file
     * @return
     */
    public static MultipartFile fileToMultipartFile(File file) {
        log.info("fileToMultipartFile文件转换中："+file.getAbsolutePath());
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item=factory.createItem(file.getName(),"text/plain",true,file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

}
